package com.qujia.web.controller.system;

import cn.hutool.core.collection.CollectionUtil;
import com.qujia.common.annotation.Log;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysRole;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.ServletUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.framework.web.service.TokenService;
import com.qujia.station.service.MemberManagementService;
import com.qujia.station.service.TeamManagementService;
import com.qujia.system.domain.SysAgent;
import com.qujia.system.service.ISysAgentService;
import com.qujia.system.service.ISysPostService;
import com.qujia.system.service.ISysRoleService;
import com.qujia.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author qujia
 */
@Api(tags = "登录用户管理", description = "登录用户管理")
@RestController
@RequestMapping("/system/user")
@Slf4j
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;
    @Autowired
    private RedisCache redisCache;


    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysAgentService sysAgentService;
    @Autowired
    private TeamManagementService teamManagementService;

    @Autowired
    private MemberManagementService memberManagementService;

    /**
     * 获取用户列表
     */
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @GetMapping("/listEnterpriseUser")
    @ApiOperation(value = "获取员工列表", notes = "获取员工列表")
    public List<SysUser> listEnterpriseUser(SysUser user)
    {

        LoginUser current=SecurityUtils.getLoginUser();
        SysUser user2 = current.getUser();

        List<SysUser> list = new ArrayList<>();

        if (null != user2.getUserLevel() && user2.getUserLevel().equals("5")){
            ArrayList<SysUser> sysUsersList= new ArrayList<>();
            log.info("输入的负责人id：{}",user2.getUserId());
            List<Long> managerEnterpriseId = teamManagementService.getManagerEnterpriseId(user2.getUserId());
            log.info("该负责人id:{} , 所管理的油企id：{}",user2.getUserId(),managerEnterpriseId);
            if (CollectionUtil.isNotEmpty(managerEnterpriseId)){
                for (Long id : managerEnterpriseId) {
                    SysUser sysUser = new SysUser();
                    sysUser.setEnterpriseId(id);
                    sysUser.setUserLevel("2");
                    List<SysUser> sysUsers = userService.selectUserList(sysUser);
                    sysUsersList.addAll(sysUsers);
                }
            }

            return sysUsersList;
        }
        if (null != user2.getUserLevel() && user2.getUserLevel().equals("6")){

            ArrayList<SysUser> sysUsersList= new ArrayList<>();
            log.info("输入的业务员id：{}",user2.getUserId());
            List<Long> managerEnterpriseId = memberManagementService.getMemberEnterpriseId(user2.getUserId());
            if (CollectionUtil.isNotEmpty(managerEnterpriseId)){
                log.info("该业务员id:{} , 所管理的油企id：{}",user2.getUserId(),managerEnterpriseId);
                for (Long id : managerEnterpriseId) {
                    SysUser sysUser = new SysUser();
                    sysUser.setEnterpriseId(id);
                    sysUser.setUserLevel("2");
                    List<SysUser> sysUsers = userService.selectUserList(sysUser);
                    sysUsersList.addAll(sysUsers);
                }
            }
            return sysUsersList;
        }
        if (null != user2.getUserLevel() && user2.getUserLevel().equals("2")){
            user.setUserLevel("2");
            user.setStationId(current.getUser().getStationId());
            user.setEnterpriseId(current.getUser().getEnterpriseId());
            return  userService.selectUserList(user);

        }

        if(current.getUser().getEnterpriseId()==null){
            list = userService.selectUserList(user);
        }else{
            user.setUserLevel("2");
            user.setEnterpriseId(current.getUser().getEnterpriseId());
            list = userService.selectUserList(user);
        }
        return list;

    }

    @GetMapping("/listUser")
    public TableDataInfo listUser(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        for(int i=0;i<list.size();i++){
            List<String> gun=new ArrayList<>();
            List<Long> gunnumber=new ArrayList<>();
            List<String> gunList1=new ArrayList<>();
            if(list.get(i).getGun()!=null){
                String [] gunls=list.get(i).getGun().split(",");
                for(String ss:gunls) {
                    gun.add(ss);
                    gunnumber.add(Long.parseLong(ss));
                }
                Long[] value=new Long[gunnumber.size()];
                for(int ss=0;ss<gunnumber.size();ss++){
                    value[ss]=gunnumber.get(ss);
                }
                Long temp=Long.parseLong("0");
                for(int tt=0;tt<value.length;tt++) {
                    for (int m = tt+1; m < value.length; m++) {
                        if(value[tt]>value[m]){
                            temp=value[m];
                            value[m]=value[tt];
                            value[tt]=temp;
                        }
                    }
                }

                for(Long mm:value){
                    gunList1.add(mm+"");
                }
            }
            if(list.get(i).getPushUserIds()!=null){
                list.get(i).setIdList(Arrays.asList(list.get(i).getPushUserIds().split(",")));
            }else {
                list.get(i).setIdList(new ArrayList<>());
            }
            list.get(i).setGunList(gunList1);

        }
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }


    /**
     * 根据用户信息获取当前的用户
     */
    @GetMapping(value = {  "/getUserInfo/{userId}" })
    public AjaxResult getUserInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        SysUser sysUser=userService.selectUserById(userId);
        if(sysUser ==null){
            return AjaxResult.error("查询用户信息失败");
        }
        if(sysUser.getPushUserIds()!=null){
            sysUser.setIdList(Arrays.asList(sysUser.getPushUserIds().split(",")));
        }else {
            sysUser.setIdList(new ArrayList<>());
        }
        if(sysUser.getGun()!=null){
            sysUser.setGunList(Arrays.asList(sysUser.getGun().split(",")));
        }else {
            sysUser.setGunList(new ArrayList<>());
        }
        return AjaxResult.success(sysUser);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if(user.getStationId()!=null){
            redisCache.deleteObject("push:emplist:"+user.getStationId());

        }
        return toAjax(userService.insertUser(user));
    }
    @ApiOperation("修改员工信息")
    @ApiImplicitParam(name = "sysUser", value = "新增用户信息", dataType = "SysUser")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/editUser")
    public AjaxResult editUser( @RequestBody SysUser user)
    {
        String gun="";
        String  userids="";
        userService.checkUserAllowed(user);
//        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
//        {
//            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
//        }
//        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
//        {
//            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        if(user.getGunList()!=null&&user.getGunList().size()>0){
            for(String ss:user.getGunList()){
                if("".equals(gun)){
                    gun+=ss;
                }else {
                    gun+=","+ss;
                }
            }
            user.setGun(gun);
        }
        if(user.getIdList()!=null&&user.getIdList().size()>0){
            for(String ss:user.getIdList()){
                if("".equals(userids)){
                    userids+=ss;
                }else {
                    userids+=","+ss;
                }
            }
            user.setPushUserIds(userids);
        }
        Long []  roles={(long)19};
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setRoleIds(roles);
        if(user.getStationId()!=null){
            redisCache.deleteObject("push:emplist:"+user.getStationId());
            redisCache.deleteObject("userid:"+user.getUserId());
            redisCache.deleteObject( "price:"+ user.getStationId()+":"+user.getUserId() );
        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        String gun="";
        userService.checkUserAllowed(user);
//        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
//        {
//            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
//        }
//        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
//        {
//            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        if(user.getGunList()!=null&&user.getGunList().size()>0){
            for(String ss:user.getGunList()){
                if("".equals(gun)){
                    gun+=ss;
                }else {
                    gun+=","+ss;
                }
            }
            user.setGun(gun);
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        if(user.getStationId()!=null){
            redisCache.deleteObject("push:emplist:"+user.getStationId());
            redisCache.deleteObject("userid:"+user.getUserId());
            redisCache.deleteObject( "price:"+ user.getStationId()+":"+user.getUserId() );
        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
       int  i = userService.deleteUserByIds(userIds);
       if(userIds!=null &&userIds.length>0){
           for(Long id :userIds){
               SysAgent sysAgent =new SysAgent();
               sysAgent.setUserId(id);
               sysAgentService.deleteSysAgent(sysAgent);
           }
       }
        return toAjax(i);
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 代理开启修改
     */
    @Log(title = "修改用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeAgentFlag")
    @Transactional
    public AjaxResult changeAgentFlag(@RequestBody SysUser user)
    {
        int i=0;
        try {
            user.setUpdateBy(SecurityUtils.getUsername());
            if(user.getAgentFlag()!=null && user.getAgentFlag().equals("0")&& user.getUserId()!=null ){
                i= userService.updateUserAgentFlag(user);
                SysAgent sysAgent =new SysAgent();
                sysAgent.setUserId(user.getUserId());
                sysAgentService.deleteSysAgent(sysAgent);
            }else if(user.getAgentFlag()!=null && user.getAgentFlag().equals("1")){
                i= userService.updateUserAgentFlag(user);
            }
        }catch (Exception e){
            System.out.println("代理开启权限"+e.getLocalizedMessage()+"");
            e.printStackTrace();
        }

        return toAjax(i);
    }

}
